package com.alan.wifishare.presenter.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @className: ALAbstractProxy
 * @describtion: ALAbstractProxy
 * @author: AlanWang
 * @email: 850267876@qq.com
 * @time: 2016/5/6 17:36
 */
public abstract class ALAbstractProxy<T> implements InvocationHandler {
    private T targert;
    private T apiInstance;
    private boolean isAllowInvoke = true;

    public ALAbstractProxy(T targert) {
        this.targert = targert;
        apiInstance = (T) Proxy.newProxyInstance(this.targert.getClass().getClassLoader(), this.targert.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object object, Method method, Object[] objects) throws Throwable {
        isAllowInvoke = true;//默认每个方法均可代理执行，如果有执行条件需在doBefore中判断，且如果不满足执行条件则将isAllowInvoke置为false
        doBefore(targert, method, objects);
        Object result = null;
        try {
            if(isAllowInvoke){
                result = method.invoke(targert, objects);
            }
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        }  finally {
            doAfter(targert, method, objects);
        }
        return result;
    }

    protected boolean isAllowInvoke() {
        return isAllowInvoke;
    }

    protected void setAllowInvoke(boolean allowInvoke) {
        isAllowInvoke = allowInvoke;
    }

    /**
     * 在执行方法之前
     * @param object
     * @param method
     * @param objects
     */
    protected abstract void doBefore(T object, Method method, Object[] objects) ;

    /**
     * 在执行方法之后
     * @param object
     * @param method
     * @param objects
     */
    protected abstract void doAfter(T object, Method method, Object[] objects) ;

    public T getApiInstance() {
        return apiInstance;
    }

}
